<template>
  <el-dialog v-model="dialogTableVisible4" :show-close="true" width="60%">
    <div style="height: 465px; overflow: hidden">
      <div style="position: absolute; top: 5px">
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="inputK3Bm"
          placeholder="k3编码"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="inputK3Mc"
          placeholder="k3名称"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-button
          style="margin-left: 5px"
          @click="searc3Kh"
          v-if="searc3KhPermissions7"
          type="primary"
          >查询</el-button
        >
        <el-button
          style="margin-left: 5px"
          @click="put3Kh"
          v-if="put3KhPermissions7"
          type="primary"
          >添加</el-button
        >
        <el-button
          style="margin-left: 5px"
          @click="updateK3"
          v-if="updateK3Permissions7"
          type="success"
          >更新k3</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData3"
          @row-click="RowClick3"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="420px"
          height="420px"
          @selection-change="handleSelectionChange1"
          show-overflow-tooltip
        >
          <el-table-column type="selection" width="65" align="center" />
          <el-table-column prop="mid" label="Id" width="80" align="center" />
          <el-table-column
            prop="partSingleId"
            label="单件唯一码"
            width="120"
            align="center"
          />
          <el-table-column prop="specification" label="型号" width="150" align="center" />
          <el-table-column
            prop="workingFaceLength"
            label="工作面长度"
            width="150"
            align="center"
          />
        </el-table>

        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="page2"
            v-model:page-size="limit2"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total3"
            @size-change="handleSizeChange3"
            @current-change="handleCurrentChange3"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <!--dialog5-->
  <el-dialog
    v-model="dialogTableVisible2"
    :show-close="true"
    width="60%"
    style="z-index: 100"
  >
    <div style="height: 465px; overflow: hidden">
      <div style="top: 5px">
        <el-input style="width: 150px; margin-left: 2px" v-model="ID" placeholder="id">
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 150px; margin-left: 2px"
          v-model="tableName"
          placeholder="表名"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>

        <el-button style="margin-left: 5px" @click="geSysStatus" type="primary"
          >查询</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData2"
          @row-click="RowClick2"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="420px"
          height="420px"
          @selection-change="handleSelectionChange2"
          show-overflow-tooltip
        >
          <el-table-column fixed type="index" width="60" align="center" />
          <el-table-column fixed type="selection" width="50" align="center" />
          <el-table-column prop="id" label="id" width="50" align="center" />
          <el-table-column prop="djNumber" label="单据编号" width="50" align="center" />
          <el-table-column
            prop="equipmentStructureId"
            label="设备结构id"
            width="100"
            align="center"
          />
          <el-table-column
            prop="categoryOfConsumables"
            label="耗材类别"
            width="100"
            align="center"
          />
          <el-table-column
            prop="businessProjectId"
            label="零件id"
            width="100"
            align="center"
          />
          <el-table-column prop="direction" label="说明" width="100" align="left" />
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="page2"
            v-model:page-size="limit2"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total2"
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 添加 -->

  <div
    v-if="dialogTableVisible"
    :width="screenWidth + 20 + 'px'"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 80;

      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div
      :style="{
        width: screenWidth - 96.5 + 'px',
        backgroundColor: 'white',
        zIndex: 8001,
      }"
    >
      <div
        :style="{
          height: screenHeight - 43.5 + 'px',
          borderBottom: '1px solid #ccc',
          width: '100%',
          backgroundColor: 'white',
          zIndex: 8002,
          display: 'flex',
          flexDirection: 'column',
        }"
      >
        <div
          ref="buttonDiv"
          style="
            background-color: white;
            z-index: 82;
            display: flex;
            margin-left: auto;
            height: 32px;
          "
        >
          <el-button @click="addRow" v-if="addRowPermissions8" type="primary"
            >增行</el-button
          >
          <el-button
            @click="getDeleteRowData"
            v-if="getDeleteRowDataPermissions8"
            type="danger"
            >删除</el-button
          >
          <el-button
            type="primary"
            @click="updateMaterialsFixed"
            v-if="showInsertButton && insertMaterialsFixedPermissions8"
            >修改</el-button
          >
          <el-button
            type="primary"
            @click="updateMaterialsFixed"
            v-if="!showInsertButton && updateMaterialsFixedPermissions8"
            >修改</el-button
          >
          <el-button
            @click="OFFdialogTableVisible"
            v-if="OFFdialogTableVisiblePermissions8"
            type="danger"
            >关闭</el-button
          >
        </div>
        <div
          ref="mBeginDiv"
          :style="{
            backgroundColor: 'rgba(247, 247, 247, 0.903)',
            height: 69 + 'px',
            width: screenWidth - 96.5 + 'px',
          }"
        >
          <el-form :model="form" class="demo-form-inline" :inline="true">
            <el-row>
              <el-form-item class="labs" style="margin-right: 0">
                <label
                  class="lab"
                  style="width: 50px; padding-right: -5px; padding-left: 55px"
                  >单号</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.djNumber"
                  placeholder="自动生成"
                  disabled
                  clearable
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0" prop="parentID">
                <label class="lab" style="width: 100px; padding-right: 5px">
                  <span style="color: red; font-weight: 700">*</span>结构ID</label
                >
                <el-input
                  style="width: 100px"
                  @click="openBusiness(index)"
                  :readonly="true"
                  v-model="form.equipmentStructureId"
                  placeholder=""
                  clearable
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>编组装置</label
                >
                <el-select
                  v-model="groupingDevice"
                  size="medium"
                  style="width: 100px"
                  clearable
                  @change="clickOrganizationStatus(index)"
                >
                  <el-option
                    v-for="item in optionss"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px">
                  <span style="color: red; font-weight: 700">*</span>零件ID</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.componentId"
                  placeholder=""
                  clearable
                />
              </el-form-item>

              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>零件数量</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.componentQuantity"
                  placeholder=""
                  clearable
                />
              </el-form-item>

              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>隔套数量</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.spacerQuantity"
                  placeholder=""
                  clearable
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>隔套</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.spacer"
                  placeholder=""
                  clearable
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>专用隔套</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.specialSpacer"
                  placeholder=""
                  clearable
                />
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>组号</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.groupNumber"
                  placeholder=""
                  clearable
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>单据状态</label
                >
                <el-select
                  v-model="djStatus"
                  size="medium"
                  style="width: 100px"
                  clearable
                  @change="clickOrganizationIsdel()"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>型号</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.specification"
                  placeholder=""
                  clearable
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  ><span style="color: red">*</span>耗材类别</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.categoryOfConsumables"
                  placeholder=""
                  clearable
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  >辊箱编码</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.rollBoxCode"
                  placeholder=""
                  clearable
                  :disabled="gunXiang"
                />
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  >编组状态</label
                >
                <el-select
                  v-model="form.groupingStatus"
                  size="medium"
                  style="width: 100px"
                  clearable
                >
                  <el-option label="在用" value="1"></el-option>
                  <el-option label="停用" value="2"></el-option>
                  <el-option label="作废" value="3"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="labs" style="margin-right: 0">
                <label class="lab" style="width: 100px; padding-right: 5px"
                  >原编组状态</label
                >
                <el-input
                  style="width: 100px"
                  v-model="form.originalGroupingStatus"
                  placeholder=""
                  clearable
                  :readonly="true"
                />
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <el-form :inline="true" :model="formInline">
          <div
            ref="headerTable"
            :style="{
              width: screenWidth - 96.5 + 'px',
              // height: 720+ 'px',
              'overflow-y': 'hidden',
              'overflow-x': 'hidden',
              'scrollbar-width': 'thin',
            }"
          >
            <table style="height: 35px; width: 100%">
              <tr class="sticky-header" style="z-index: 99">
                <th style="width: 50px" class="table-header">序号</th>
                <th style="width: 50px" class="table-header">
                  <el-checkbox
                    @change="toggleSelectAll"
                    v-model="selectAll"
                  ></el-checkbox>
                </th>

                <th style="width: 100px" class="table-header">变更方式</th>
                <th style="width: 100px" class="table-header">原单件ID</th>
                <th style="width: 100px" class="table-header">单件ID</th>
                <th style="width: 100px" class="table-header">单件唯一码</th>
                <th style="width: 100px" class="table-header">隔套唯一码</th>
                <th style="width: 100px" class="table-header">初始尺寸</th>
                <th style="width: 100px" class="table-header">型号</th>
                <th style="width: auto" class="table-header">说明</th>
                <th style="width: 113px" class="table-header">操作</th>
              </tr>
            </table>
          </div>
          <div
            ref="subDataDiv"
            :style="{
              height: calculatedHeight + 'px',
              width: screenWidth - 96.5 + 'px',
              'overflow-y': 'scroll',
              'overflow-x': 'hidden',
              'scrollbar-width': 'thin',
            }"
          >
            <table id="subDataTbale" style="width: 100%">
              <tr
                v-for="(formData, index) in formDataList"
                :key="index"
                style="height: 30px"
              >
                <td style="text-align: center; width: 50px">{{ index + 1 }}</td>
                <td style="text-align: center; width: 50px">
                  <el-checkbox v-model="formData.selected"></el-checkbox>
                </td>

                <td
                  class="table-value"
                  style="width: 100px; text-align: left; padding-left: 1px"
                >
                  <el-select
                    v-model="formData.changeMode"
                    size="medium"
                    style="width: 100px"
                    clearable
                  >
                    <el-option label="调整" value="1"></el-option>
                    <el-option label="调减" value="2"></el-option>
                    <el-option label="调增" value="3"></el-option>
                  </el-select>
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: center; padding-left: 1px"
                >
                  {{ formData.originalSingleId }}
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: center; padding-left: 1px"
                  @click="openWlbm(index)"
                >
                  {{ formData.singleId }}
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: center; padding-left: 1px"
                >
                  {{ formData.singleUniqueCode }}
                </td>

                <td
                  class="table-value"
                  style="width: 100px; text-align: center; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.spacerUniqueCode"
                    :readonly="true"
                    placeholder=""
                    clearable
                    width="99%"
                    :disabled="!gunXiang || !dao"
                  />
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: center; padding-left: 1px"
                >
                  {{ formData.initialSize }}
                </td>
                <td
                  class="table-value"
                  style="width: 100px; text-align: center; padding-left: 1px"
                >
                  {{ formData.specificationSub }}
                </td>
                <td
                  class="table-value"
                  style="width: auto; text-align: left; padding-left: 1px"
                >
                  <el-input
                    v-model="formData.description"
                    placeholder=""
                    clearable
                    width="99%"
                  />
                  {{ formData.description }}
                </td>
                <td style="width: 100px; text-align: left; padding-left: 1px">
                  <el-button
                    style="width: auto; margin-top: 1px"
                    type="danger"
                    @click="handleDeletes(index)"
                    >删除</el-button
                  >
                </td>
              </tr>
            </table>
          </div>

          <div
            ref="footerDiv"
            :style="{
              width: screenWidth - 96.5 + 'px',
            }"
          >
            <table style="height: 35px">
              <tr
                style="
                  text-align: center;
                  position: sticky;
                  bottom: -1px;
                  background-color: #ddd;
                  z-index: 99;
                "
              >
                <td style="width: 50px; text-align: left">合计:</td>
                <td style="width: 50px; text-align: left; padding-left: 1px"></td>
                <td style="width: 100px; text-align: left; padding-left: 1px"></td>
                <td style="width: 100px; text-align: left; padding-left: 1px"></td>
                <td style="width: 100px; text-align: left; padding-left: 1px"></td>
                <td style="width: 100px; text-align: left; padding-left: 1px"></td>
                <td style="width: 100px; text-align: left; padding-left: 1px"></td>
                <td style="width: 100px; text-align: left; padding-left: 1px"></td>
                <td style="width: auto; text-align: left; padding-left: 1px"></td>
                <td style="width: 113px; text-align: left; padding-left: 1px"></td>
              </tr>
            </table>
          </div>
        </el-form>
        <div ref="mEndDiv" style="background-color: rgba(247, 247, 247, 0.903)">
          <el-form
            :model="form"
            class="demo-form-inline"
            :inline="true"
            :style="{
              backgroundColor: ' rgba(247, 247, 247, 0.903)',
              width: screenWidth - 96.5 + 'px',
              height: '50px',
            }"
          >
            <el-form-item class="lab" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">备注</label>
              <el-input
                :style="{
                  width: screenWidth - 96.5 - 100 - 5 + 'px',
                  zIndex: '99',
                  backgroundColor: '#ffffff',
                  resize: 'none',
                  height: '45px',
                }"
                type="textarea"
                v-model="form.bz"
                placeholder="备注"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">制单人</label>
              <el-input
                v-model="form.zdr"
                style="width: 200px; height: 35px"
                disabled
                placeholder="制单人"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">制单时间</label>
              <el-config-provider :locale="locale">
                <el-date-picker
                  style="width: 200px"
                  disabled
                  v-model="form.zdsj"
                  type="datetime"
                  placeholder="制单时间"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">修改人</label>
              <el-input
                style="width: 180px"
                v-model="form.xgr"
                disabled
                placeholder="修改人"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">修改时间</label>
              <el-config-provider :locale="locale">
                <el-date-picker
                  style="width: 200px"
                  disabled
                  v-model="form.xgsj"
                  type="datetime"
                  placeholder="修改时间"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">审核人</label>
              <el-input
                style="width: 200px"
                v-model="form.shr"
                disabled
                placeholder="审核人"
                clearable
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0; height: 3.5vh">
              <label class="lab" style="width: 100px; padding-right: 5px"
                >审核时间:</label
              >
              <el-config-provider :locale="locale">
                <el-date-picker
                  style="width: 200px"
                  disabled
                  v-model="form.shsj"
                  type="datetime"
                  placeholder="审核时间"
                />
              </el-config-provider>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>

  <!-- 页面布局 -->
  <div>
    <el-container>
      <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
        <!-- 头部按钮 -->
        <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
          <div style="display: flex; align-items: center">
            <el-button
              @click="searchButton"
              v-if="searchButtonPermissions8"
              type="primary"
            >
              查询</el-button
            >
            <el-button
              @click="handleAudit"
              v-if="searchButtonPermissions8"
              type="primary"
            >
              审核</el-button
            >
            <el-button @click="handleDelete" v-if="handleDeletePermissions8" type="danger"
              >删除</el-button
            >
          </div>
          <!-- <div class="title">包材需求计算</div> -->
        </el-row>
        <div
          style="margin-left:5.6rem;height: 30px;width=100%; background:rgb(241,244,243);margin-bottom: 0;position: relative; display: flex; justify-content: flex-start;"
        >
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="id"
            placeholder="id"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="businessProjectId"
            placeholder="业务项目id"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-header>
      <el-container>
        <el-container>
          <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
            <el-table
              v-loading="loading"
              ref="table"
              :data="tableData"
              border
              stripe
              :header-cell-style="headerCellStyle"
              @selection-change="handleSelectionChange"
              @row-dblclick="handleRowClick"
              @row-click="RowClick"
              :row-style="rowState"
              :row-key="(row) => row.id"
              :max-height="screenHeight"
              :height="screenHeight - 135 + 'px'"
              empty-text="无数据"
            >
              <el-table-column fixed type="index" width="60" align="center" />
              <el-table-column fixed type="selection" width="50" align="center" />
              <el-table-column fixed prop="id" label="ID" width="100" align="center" />
              <el-table-column
                prop="equipmentStructureId"
                label="结构ID"
                width="100"
                align="center"
              />

              <el-table-column prop="groupId" label="组ID" width="100" align="left" />
              <el-table-column
                prop="groupNumber"
                label="组号"
                width="100"
                align="center"
              />
              <el-table-column
                prop="componentId"
                label="零件ID"
                width="100"
                align="left"
              />
              <el-table-column
                prop="componentQuantity"
                label="零件数量"
                width="100"
                align="center"
              />
              <el-table-column
                prop="categoryOfConsumables"
                label="耗材类别"
                width="100"
                align="center"
              />
              <el-table-column
                prop="specification"
                label="型号"
                width="100"
                align="left"
              />

              <el-table-column prop="spacer" label="隔套" width="100" align="center" />
              <el-table-column
                prop="specialSpacer"
                label="专用隔套"
                width="100"
                align="left"
              />
              <el-table-column
                prop="spacerQuantity"
                label="隔套数量"
                width="100"
                align="left"
              />

              <el-table-column
                prop="rollBoxCode"
                label="辊箱编码"
                width="100"
                align="left"
              />
              <el-table-column
                prop="groupingDevice"
                label="编组装置"
                width="100"
                align="center"
              />

              <el-table-column
                fixed="right"
                prop="status"
                label="状态"
                width="100"
                align="center"
              />
            </el-table>
          </el-main>
          <!-- <el-footer style="background: linear-gradient(to right, #f9f9fc, #fef5f0)"
            >Footer</el-footer
          > --><el-footer style="height: 20px">
            <div class="demo-pagination-block">
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="limit"
                :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
                :small="true"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-footer>
        </el-container>
        <!-- <el-aside width="20%"></el-aside> -->
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";
import * as notifications from "../../components/utils/notification.ts";
const Permission = ref(false);
const isDdslDisabledYwy = ref(true);
const router = useRouter();
const isDdslDisabled = ref(true);
// 权限控制
const searbzfaPermissions8 = ref(false);
const searchYwyPermissions8 = ref(false);
const updatYwyPermissions8 = ref(false);
const addRowPermissions8 = ref(false);
const getDeleteRowDataPermissions8 = ref(false);
const insertMaterialsFixedPermissions8 = ref(false);
const updateMaterialsFixedPermissions8 = ref(false);
const OFFdialogTableVisiblePermissions8 = ref(false);
const searchButtonPermissions8 = ref(false);
const handleAction1Permissions8 = ref(false);
const handleWarning0Permissions8 = ref(false);
const handleWarning1Permissions8 = ref(false);
const handleDeletePermissions8 = ref(false);
const menuId = ref(8);
const buttonVariables = {
  searbzfaPermissions8,
  searchYwyPermissions8,
  updatYwyPermissions8,
  addRowPermissions8,
  getDeleteRowDataPermissions8,
  insertMaterialsFixedPermissions8,
  updateMaterialsFixedPermissions8,
  OFFdialogTableVisiblePermissions8,
  searchButtonPermissions8,
  handleAction1Permissions8,
  handleWarning0Permissions8,
  handleWarning1Permissions8,
  handleDeletePermissions8,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");

  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();

const xxx = ref();

// 计算高度
const screenHeight = ref(null);
const dynamicHeight = ref(null);
const dynamicHeightYtfl = ref(null);
const tableHeight = ref(null);

const getScreenHeight = () => {
  screenHeight.value = window.innerHeight - 146 - 42 + 55;
  dynamicHeight.value = `${window.innerHeight - 55 + 55}px`;
  dynamicHeightYtfl.value = window.innerHeight - 120 + 55;
  tableHeight.value = window.innerHeight - 435 + 19 + 55;

  console.log("高度");
  console.log("子表:" + tableHeight.value);
};
getScreenHeight();

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
const activeIndex = ref("1");
const handleSelect = (key: string, keyPath: string[]) => {};
const dialogTableVisible = ref(false);
const dialogTableVisible1 = ref(false);
const dialogTableVisible2 = ref(false);
const dialogTableVisible3 = ref(false);
const dialogTableVisible4 = ref(false);
const dialogTableVisible5 = ref(false);
//声明类
const formInline = ref([]);
const ddslinput = ref(null);
const isPrinting = ref(false);
const djStatus = ref("");
const selectedRows = ref([]);
const id = ref("");
const changeMode = ref("");
const tableName = ref("");
const status = ref("");
const businessProjectId = ref("");
const groupingDevice = ref("");
const parameterItemId = ref("");
const itemType = ref("");
const description = ref("");
const direction = ref("");
const verticalLine3 = ref(null);
const tableData = ref([]);
const tableData1 = ref([]);
const tableData3 = ref([]);
const tableData4 = ref([]);
const tableData5 = ref([]);
const checkList = ref([]);
const checkList1 = ref([]);
const showInsertButton = ref(true);
const screenWidth = ref(window.innerWidth);

const inputHeight = ref(200);
// 头部按钮
const table = ref();
const rowTable = ref([]);
//子表
const selectedRowIndex = ref(-1); // 初始化为-1，表示没有选中的行
let clearSelection = true;
//多选
const selectAll = ref(false);
// 分页
const page = ref(1);
const page1 = ref(1);
const page2 = ref(1);
const page3 = ref(1);
const page4 = ref(1);
const page5 = ref(1);
const limit = ref(50);
const limit1 = ref(50);
const limit2 = ref(50);
const limit3 = ref(50);
const limit4 = ref(50);
const limit5 = ref(50);
const total = ref(10);
const total1 = ref(10);
const total2 = ref(10);
const total3 = ref(10);
const total4 = ref(10);
const total5 = ref(10);
const loading = ref(false);

// // 设置表头样式
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  textAlign: "center",
  // padding: "0 0 0 30px",
};
//方法类
const selectCookies = () => {};
selectCookies();
const handleResize = () => {
  screenWidth.value = window.innerWidth;
  console.log("宽度" + screenWidth.value);
  // screenWidth.value = screenWidth.value - 96;
  screenHeight.value = window.innerHeight;
  inputHeight.value = 50;
  console.log(screenHeight.value + "高度1");
};
handleResize();
const handleRowClick = (row) => {
  // isDdslDisabled.value = false;
  // isDdslDisabledYwy.value = true;
  dialogTableVisible.value = true;
  showInsertButton.value = false;
  form.id = row.id;
  form.equipmentStructureId = row.equipmentStructureId;
  form.componentId = row.componentId;
  form.componentQuantity = row.componentQuantity;
  form.spacerQuantity = row.spacerQuantity;
  form.spacer = row.spacer;
  form.specialSpacer = row.specialSpacer;
  form.groupNumber = row.groupNumber;
  form.rollBoxCode = row.rollBoxCode;
  groupingDevice.value = row.groupingDevice;
  form.specification = row.specification;
  form.groupId = row.groupId;
  form.categoryOfConsumables = row.categoryOfConsumables;
  form.originalGroupingStatus = row.status;
  const userName = Cookies.get("userName");
  const currentFormattedDateTime = getCurrentFormattedDateTime();
  const currentFormattedDate = getCurrentFormattedDate();
  form.xgsj = currentFormattedDateTime;
  form.xgr = userName;

  nextTick(() => {
    const height = buttonDiv.value.clientHeight;
    const height1 = mBeginDiv.value.clientHeight;
    const height2 = headerTable.value.clientHeight;
    const height3 = subDataDiv.value.clientHeight;
    const height4 = footerDiv.value.clientHeight;
    const height5 = mEndDiv.value.clientHeight;
    const totalHeight = document.body.scrollHeight;
    console.log(
      "buttonDiv" + height,
      "mBeginDiv" + height1,
      "headerTable" + height2,
      "subDataDiv" + height3,
      "footerDiv" + height4,
      "mEndDiv" + height5,
      "totalHeight" + totalHeight
    );
    const heightSum = height + height1 + height2 + height4 + height5;

    const calculatedHeight = totalHeight - heightSum - 75;
    subDataDiv.value.style.height = `${calculatedHeight}px`;

    console.log("Calculated height:", calculatedHeight);
  });
  // 回显测算类型
  // 回显子表
  axios({
    url: "/select/ComponentGroupBasicSubTable",
    method: "post",
    data: {
      id: form.id,
    },
  }).then((res) => {
    const testList = res.data;
    console.log(testList);

    if (testList.length === 0) {
      for (let a = 0; a < 21; a++) {
        addRow();
      }
    } else {
      const formattedData = testList.map((test, index) => ({
        autoId: test.autoId,
        id: test.id,
        mid: test.mid,
        originalSingleId: test.singleId,
        singleId: test.singleId,
        singleUniqueCode: test.singleUniqueCode,
        spacerUniqueCode: test.spacerUniqueCode,
        initialSize: test.initialSize,
        specificationSub: test.specificationSub,
        changeMode: test.changeMode,
      }));
      formDataList.value = formattedData;
    }
    console.log(formDataList.value);
  });
};
const buttonDiv = ref();
const mBeginDiv = ref();
const headerTable = ref();
const subDataDiv = ref();
const footerDiv = ref();
const mEndDiv = ref();
const calculatedHeight = ref(null);
const handleAction1 = function () {
  dialogTableVisible.value = true;
  isDdslDisabled.value = true;
  isDdslDisabledYwy.value = false;
  showInsertButton.value = true;

  nextTick(() => {
    const height = buttonDiv.value.clientHeight;
    const height1 = mBeginDiv.value.clientHeight;
    const height2 = headerTable.value.clientHeight;
    const height3 = subDataDiv.value.clientHeight;
    const height4 = footerDiv.value.clientHeight;
    const height5 = mEndDiv.value.clientHeight;
    const totalHeight = document.body.scrollHeight;
    console.log(
      "buttonDiv" + height,
      "mBeginDiv" + height1,
      "headerTable" + height2,
      "subDataDiv" + height3,
      "footerDiv" + height4,
      "mEndDiv" + height5,
      "totalHeight" + totalHeight
    );
    const heightSum = height + height1 + height2 + height4 + height5;

    const calculatedHeight = totalHeight - heightSum - 75;
    subDataDiv.value.style.height = `${calculatedHeight}px`;

    console.log("Calculated height:", calculatedHeight);
  });
};

// 关闭弹窗
const OFFdialogTableVisible = () => {
  dialogTableVisible.value = false;
  showInsertButton.value = true;

  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  (checkList.value = ""), (checkList1.value = "");
  // 删除
  formDataList.value = [];
  // location.reload();
  page1.value = 1;
  page2.value = 1;
  page3.value = 1;
  page4.value = 1;
  page5.value = 1;
  limit1.value = 50;
  limit2.value = 50;
  limit3.value = 50;
  limit4.value = 50;
  limit5.value = 50;
};
// 进入页面
const selectpurposes = () => {
  // 查看是否登录
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  axios({
    url: "/select/ComponentGroupBasicMainTable",
    method: "post",
    data: {
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    const testList = res.data;
    if (testList.length == 0) {
      loading.value = false;
      return;
    }
    total.value = res.data[0].total;

    tableData.value = testList.map((test) => ({
      // 根据 djzt 的值设置状态
      // zt: test.zt === 0 ? "待审" : "已审核",
      autoId: test.autoId,
      id: test.id,
      equipmentStructureId: test.equipmentStructureId,
      componentId: test.componentId,
      componentQuantity: test.componentQuantity,
      spacerQuantity: test.spacerQuantity,
      spacer: test.spacer,
      specialSpacer: test.specialSpacer,
      groupId: test.groupId,
      groupNumber: test.groupNumber,
      rollBoxCode: test.rollBoxCode,
      groupingDevice: test.groupingDevice,
      djNumber: test.djNumber,
      djStatus: test.djStatus,
      specification: test.specification,
      categoryOfConsumables: test.categoryOfConsumables,
      status: test.status,
    }));

    for (let a = 0; a < 20; a++) {
      addRow();
    }
    //制单人
    form.zdr = userName;
    // 制单时间
    const currentFormattedDateTime = getCurrentFormattedDateTime();
    const currentFormattedDate = getCurrentFormattedDate();
    form.zdsj = currentFormattedDateTime;
    loading.value = false;
  });
  loading.value = true;
};

const RowClick1 = (row, selection) => {
  form.testName = row.testName;
  dialogTableVisible1.value = false;
};
const formDataList = ref([
  {
    id: "",
    mid: "",
    singleId: "",
    singleUniqueCode: "",
    spacerUniqueCode: "",
    initialSize: "",
    specificationSub: "",
    originalSingleId: "",
    changeMode: "",
    selected: false,
  },
]);
const form = reactive({
  id: "",
  equipmentStructureId: "",
  componentId: "",
  componentQuantity: "",
  spacerQuantity: "",
  spacer: "",
  specialSpacer: "",
  groupNumber: "",
  rollBoxCode: "",
  groupingDevice: "",
  djNumber: "",
  djStatus: "",
  specification: "",
  categoryOfConsumables: "",
  groupingStatus: "",
  originalGroupingStatus: "",
  zdr: "",
  zdsj: "",
  xgr: "",
  xgsj: "",
  shr: "",
  shsj: "",
});
const addRow = () => {
  formDataList.value.push({
    id: "",
    mid: "",
    singleId: "",
    singleUniqueCode: "",
    spacerUniqueCode: "",
    initialSize: "",
    specificationSub: "",
    originalSingleId: "",
    changeMode: "",
    selected: false,
  });

  console.log(
    "网页可见区域宽：" + document.body.clientWidth,
    "网页可见区域高：" + document.body.clientHeight,
    "网页可见区域宽：" + document.body.offsetWidth,
    "网页可见区域高：" + document.body.offsetHeight,
    "网页正文全文宽：" + document.body.scrollWidth,
    "网页正文全文高：" + document.body.scrollHeight,
    "网页被卷去的高：" + document.body.scrollTop,
    "网页被卷去的左：" + document.body.scrollLeft,
    "网页正文部分上：" + window.screenTop,
    "网页正文部分左：" + window.screenLeft,
    "屏幕分辨率的高：" + window.screen.height,
    "屏幕分辨率的宽：" + window.screen.width,
    "屏幕可用工作区高度：" + window.screen.availHeight,
    "屏幕可用工作区宽度：" + window.screen.availWidth
  );
};
const getK3vm = () => {
  axios({
    url: "/select/SingSub",
    method: "post",
    data: {
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    tableData3.value = res.data;
    if (res.data.length == 0) {
      total3.value == 0;
      return;
    }
    total3.value = res.data[0].total;
  });
};

var indexK3bm = 0;
const openWlbm = (index) => {
  indexK3bm = index;
  console.log(indexK3bm);
  dialogTableVisible4.value = true;
  getK3vm();
};
const handleSizeChange3 = (val: number) => {
  axios({
    url: "/select/SingSub",
    method: "post",
    data: {
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    tableData3.value = res.data;
    if (res.data.length == 0) {
      total3.value == 0;
      return;
    }
    total3.value = res.data[0].total;
  });
};
const handleCurrentChange3 = (val: number) => {
  axios({
    url: "/select/SingSub",
    method: "post",
    data: {
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    tableData3.value = res.data;
    if (res.data.length == 0) {
      total3.value == 0;
      return;
    }
    total3.value = res.data[0].total;
  });
};
const RowClick3 = (row) => {
  console.log(formDataList.value[indexK3bm].wlbm);
  formDataList.value[indexK3bm].singleId = row.mid;
  formDataList.value[indexK3bm].singleUniqueCode = row.partSingleId;
  formDataList.value[indexK3bm].spacerUniqueCode = row.partSingleId;
  formDataList.value[indexK3bm].initialSize = row.workingFaceLength;
  formDataList.value[indexK3bm].specificationSub = row.specification;
  dialogTableVisible4.value = false;
};
const tableData2 = ref([]);
const openBusiness = (index) => {
  dialogTableVisible2.value = true;
  geSysStatus();
};
const handleSizeChange2 = (val: number) => {
  geSysStatus();
};
const handleCurrentChange2 = (val: number) => {
  geSysStatus();
};
const selectedRows2 = ref([]);
const handleSelectionChange2 = (val) => {
  selectedRows2.value = val;
};
const geSysStatus = () => {
  axios({
    url: "/select/Single",
    method: "post",
    data: {
      id: id.value,
      page: page2.value,
      limit: limit2.value,
    },
  }).then((res) => {
    const statusList = res.data;
    tableData2.value = [];
    if (statusList.length == 0) {
      total2.value = 0;
      return;
    }
    total2.value = statusList[0].total;
    tableData2.value = statusList.map((test) => ({
      // 根据 djzt 的值设置状态
      // zt: test.zt === 0 ? "待审" : "已审核",
      autoId: test.autoId,
      id: test.id,
      categoryOfConsumables: test.categoryOfConsumables,
      equipmentStructureId: test.equipmentStructureId,
      businessProjectId: test.businessProjectId,
      djNumber: test.djNumber,
      description: test.description,
    }));
  });
};
const RowClick2 = (row, selection) => {
  (form.id = row), id;
  form.equipmentStructureId = row.equipmentStructureId;
  form.componentId = row.businessProjectId;
  form.categoryOfConsumables = row.categoryOfConsumables;
  axios({
    url: "/select/SingleSub",
    method: "post",
    data: {
      id: row.djNumber,
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    const testList = res.data;
    console.log(res.data);
    console.log(form);
    if (testList.length == 0) {
      loading.value = false;
      return;
    }
    total.value = res.data[0].total;
    // 根据 djzt 的值设置状态
    // zt: test.zt === 0 ? "待审" : "已审核",
    console.log(res.data[0]);
    form.specification = res.data[0].specification;
    if (testList.length > 0) {
      for (let a = 0; a < testList.length; a++) {
        formDataList.value[a].singleId = testList[a].mid;
        formDataList.value[a].singleUniqueCode = testList[a].partSingleId;
        formDataList.value[a].spacerUniqueCode = testList[a].partSingleId;
        formDataList.value[a].initialSize = testList[a].workingFaceLength;
        formDataList.value[a].specificationSub = testList[a].specification;
      }
      console.log(res.data);
    }
  });
  dialogTableVisible2.value = false;
};

const windowBzfa = () => {
  dialogTableVisible5.value = true;
};
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    // #E9E9E7
    // D9D9D7   C9C9C7 A9A9A7
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};

// 查询
const searchButton = () => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/select/ComponentGroupBasicMainTable",
      method: "post",
      data: {
        id: id.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        total.value = 0;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        autoId: test.autoId,
        id: test.id,
        equipmentStructureId: test.equipmentStructureId,
        componentId: test.componentId,
        componentQuantity: test.componentQuantity,
        spacerQuantity: test.spacerQuantity,
        spacer: test.spacer,
        specialSpacer: test.specialSpacer,
        groupId: test.groupId,
        groupNumber: test.groupNumber,
        rollBoxCode: test.rollBoxCode,
        groupingDevice: test.groupingDevice,
        djNumber: test.djNumber,
        djStatus: test.djStatus,
        specification: test.specification,
        categoryOfConsumables: test.categoryOfConsumables,
        status: test.status,
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      // form.djrq = currentFormattedDate;
      loading.value = false;
    });
  });
  loading.value = true;
};
const gunXiang = ref(true);
const dao = ref(true);
const clickOrganizationStatus = (index) => {
  console.log(index);
  form.groupingDevice = groupingDevice.value;
  if (groupingDevice.value == 1) {
    dao.value = false;
    gunXiang.value = true;
    formDataList.value.forEach((item, index) => {
      item.spacerUniqueCode = "";
    });
  }
  if (groupingDevice.value == 2) {
    gunXiang.value = false;
    dao.value = true;
    formDataList.value.forEach((item, index) => {
      item.spacerUniqueCode = "";
    });
  }
};
const clickChangeMode = (index) => {
  console.log("formDataList.value[index].changeMode=" + formDataList.value.changeMode);
  formDataList.value.changeMode = changeMode.value;
};
const handleSizeChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/select/ComponentGroupBasicMainTable",
      method: "post",
      data: {
        id: id.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        autoId: test.autoId,
        id: test.id,
        equipmentStructureId: test.equipmentStructureId,
        componentId: test.componentId,
        componentQuantity: test.componentQuantity,
        spacerQuantity: test.spacerQuantity,
        spacer: test.spacer,
        specialSpacer: test.specialSpacer,
        groupId: test.groupId,
        groupNumber: test.groupNumber,
        rollBoxCode: test.rollBoxCode,
        groupingDevice: test.groupingDevice,
        djNumber: test.djNumber,
        djStatus: test.djStatus,
        specification: test.specification,
        categoryOfConsumables: test.categoryOfConsumables,
        status: test.status,
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      loading.value = false;
    });
  });
  loading.value = true;
};
const handleCurrentChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/select/ComponentGroupBasicMainTable",
      method: "post",
      data: {
        id: id.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        autoId: test.autoId,
        id: test.id,
        equipmentStructureId: test.equipmentStructureId,
        componentId: test.componentId,
        componentQuantity: test.componentQuantity,
        spacerQuantity: test.spacerQuantity,
        spacer: test.spacer,
        specialSpacer: test.specialSpacer,
        groupId: test.groupId,
        groupNumber: test.groupNumber,
        rollBoxCode: test.rollBoxCode,
        groupingDevice: test.groupingDevice,
        djNumber: test.djNumber,
        djStatus: test.djStatus,
        specification: test.specification,
        categoryOfConsumables: test.categoryOfConsumables,
        status: test.status,
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      // form.djrq = currentFormattedDate;
      loading.value = false;
    });
  });
  loading.value = true;
};
const parentIDValue = ref("");
const parentIDOptions = ref([]);

const requestData = computed(() => ({}));

const updateMaterialsFixed = () => {
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  if (form.equipmentStructureId == "") {
    alert("请选择设备结构id！");
    return;
  }
  if (groupingDevice.value == "") {
    alert("请先选择编组装置！");
    return;
  }
  if (djStatus.value == "") {
    alert("请选择单据状态！");
    return;
  }

  const textinfo = ref(1);
  const flag = ref(0);
  formDataList.value.forEach((item, key) => {
    if (item["singleId"] == "") {
      return;
    }
    console.log("第" + (key + 1) + "行字段名称=" + item["targetState"]);
    const text = ref("");
    //  if (item["changeMode"] == "") {
    //    text.value = text.value == "" ? "变更方式" : text.value + "," + "变更方式";
    //  }
    flag.value = 1;
    if (text.value != "") {
      textinfo.value =
        textinfo.value == 1
          ? "第 " + (key + 1) + " 行请输入:[" + text.value + "];" + "\n"
          : textinfo.value + "第 " + (key + 1) + " 行请输入:[" + text.value + "];" + "\n";
    }
  });

  if (textinfo.value != 1) {
    alert(textinfo.value);
    return;
  }
  if (flag.value == 0) {
    alert("请输入数据！");
  }

  if (confirm("确认修改吗？") == false) {
    return;
  }
  const requestData = ref([]);
  formDataList.value.forEach((item, key) => {
    if (item["singleId"] == "") {
      return;
    }
    requestData.value[requestData.value.length] = item;
  });
  // 显示确认弹窗
  axios({
    url: "/update/ComponentGroup",
    method: "post",
    data: {
      id: form.id,
      equipmentStructureId: form.equipmentStructureId,
      componentId: form.componentId,
      componentQuantity: form.componentQuantity,
      spacerQuantity: form.spacerQuantity,
      spacer: form.spacer,
      specialSpacer: form.specialSpacer,
      groupNumber: form.groupNumber,
      rollBoxCode: form.rollBoxCode,
      groupingDevice: groupingDevice.value,
      djNumber: form.djNumber,
      djStatus: djStatus.value,
      specification: form.specification,
      categoryOfConsumables: form.categoryOfConsumables,
      groupingStatus: form.groupingStatus,
      originalGroupingStatus: form.originalGroupingStatus,
      userName: userName,
      requestData: requestData.value,
    },
  }).then((res) => {
    if (res.data.data == 200) {
      // location.reload();
      ElMessage({
        center: true,
        showClose: true,
        grouping: true,
        offset: window.screen.height / 9,
        message: "修改成功",
        type: "success",
      });
      OFFdialogTableVisible();
      selectpurposes();
      return;
    }
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "修改失败",
      type: "error",
    });
  });
};

const optionx = reactive([
  {
    value: "1",
    label: "调整",
  },
  {
    value: "2",
    label: "调减",
  },
  {
    value: "3",
    label: "调增",
  },
]);
const optionss = reactive([
  {
    value: "1",
    label: "刀轴",
  },
  {
    value: "2",
    label: "辊箱",
  },
]);
const clickOrganizationIsdel = () => {
  form.djStatus = djStatus.value;
};

const options = reactive([
  {
    value: "0",
    label: "未审核",
  },
  {
    value: "1",
    label: "已审核",
  },
]);

const indexEmployeeJob = ref(0);

const handleRowDatas = (row) => {};
// 新增
const insertMaterialsFixed = () => {
  //   const userName = Cookies.get("userName");
  //   if (itemType.value == "") {
  //     alert("请先选择项目类型！");
  //     return;
  //   }
  //   if (form.businessProjectId == "") {
  //     alert("请选择业务项目id！");
  //     return;
  //   }
  //   if (status.value == "") {
  //     alert("请选择状态！");
  //     return;
  //   }

  const textinfo = ref(1);
  const flag = ref(0);
  formDataList.value.forEach((item, key) => {
    if (item["singleId"] == "") {
      return;
    }
    console.log("第" + (key + 1) + "行业务项目id=" + item["singleId"]);
    const text = ref("");
    //  if (item["currentState"] == "") {
    //    text.value = text.value == "" ? "当前状态" : text.value + "," + "当前状态";
    //  }
    //  if (item["status"] == "") {
    //    text.value = text.value == "" ? "状态" : text.value + "," + "状态";
    //  }
    flag.value = 1;
    if (text.value != "") {
      textinfo.value =
        textinfo.value == 1
          ? "第 " + (key + 1) + " 行请输入:[" + text.value + "];" + "\n"
          : textinfo.value + "第 " + (key + 1) + " 行请输入:[" + text.value + "];" + "\n";
    }
  });

  if (textinfo.value != 1) {
    alert(textinfo.value);
    return;
  }
  if (flag.value == 0) {
    alert("请输入数据！");
  }

  if (confirm("确认保存吗？") == false) {
    return;
  }
  const requestData = ref([]);
  formDataList.value.forEach((item, key) => {
    if (item["singleId"] == "") {
      return;
    }
    requestData.value[requestData.value.length] = item;
  });

  axios({
    url: "/insert/ComponentGroup",
    method: "post",
    data: {
      equipmentStructureId: form.equipmentStructureId,
      componentId: form.componentId,
      componentQuantity: form.componentQuantity,
      spacerQuantity: form.spacerQuantity,
      spacer: form.spacer,
      specialSpacer: form.specialSpacer,
      groupNumber: form.groupNumber,
      rollBoxCode: form.rollBoxCode,
      groupingDevice: form.groupingDevice,
      djNumber: form.djNumber,
      djStatus: form.djStatus,
      specification: form.specification,
      categoryOfConsumables: form.categoryOfConsumables,
      requestData: requestData.value,
    },
  }).then((res) => {
    if (res.data.data == 200) {
      // location.reload();
      ElMessage({
        center: true,
        showClose: true,
        grouping: true,
        offset: window.screen.height / 9,
        message: "保存成功",
        type: "success",
      });
      OFFdialogTableVisible();
      selectpurposes();
      return;
    }
    ElMessage({
      center: true,
      showClose: true,
      grouping: true,
      offset: window.screen.height / 9,
      message: "保存失败",
      type: "error",
    });
  });

  return;
  console
    .log(formDataList.value)
    // 显示确认弹窗

    // ElMessageBox.confirm("确认保存吗？", "提示", {
    //   confirmButtonText: "确认",
    //   cancelButtonText: "取消",
    //   type: "warning",
    //   center: true,
    // })
    .then(() => {
      const requestData = formDataList.value.map((formData) => ({
        id: formData.id,
        sequenceNumber: formData.sequenceNumber,
        tableId: formData.tableId,
        fieldName: formData.fieldName,
        fieldDescription: formData.fieldDescription,
        fieldType: formData.fieldType,
        fieldLength: formData.fieldLength,
        decimalDigits: formData.decimalDigits,
        direction: formData.direction,
        sourceMode: formData.sourceMode,
        sourceTable: formData.sourceTable,
        sourceField: formData.sourceField,
        sourceSql: formData.sourceSql,
      }));
      console.log(requestData);

      axios({
        url: "/insert/statusOperation",
        method: "post",
        data: {
          id: form.id,
          tableName: form.tableName,
          operationField: form.operationField,
          operationMenu: form.operationMenu,
          operationButton: form.operationMenu,
          precedingOperation: form.operationMenu,
          subsequentOperation: form.operationMenu,
          userName: userName,
          requestData: requestData.value,
        },
      }).then((res) => {
        if (res.data.data == 200) {
          // location.reload();
          ElMessage({
            center: true,
            showClose: true,
            grouping: true,
            offset: window.screen.height / 9,
            message: "保存成功",
            type: "success",
          });
          OFFdialogTableVisible();
          selectpurposes();

          return;
        }
        ElMessage({
          center: true,
          showClose: true,
          grouping: true,
          offset: window.screen.height / 9,
          message: "保存失败",
          type: "error",
        });
      });
    })
    .catch(() => {});
};

//审核

const printPage = () => {
  // 使用 window.print() 方法触发页面打印
  isPrinting.value = true;

  // Use the browser's print functionality
  window.print();

  // Reset the flag after printing is done
  isPrinting.value = false;
};
//弃审

const handleDeletes = (index: number) => {
  formDataList.value.splice(index, 1);

  if (formDataList.value.length === 0) {
    addRow();
  }
};
//删除已勾选
const getDeleteRowData = () => {
  const selectedIndexes: any = [];

  // 找到已勾选行的索引
  formDataList.value.forEach((formData, index) => {
    if (formData.selected) {
      selectedIndexes.push(index);
    }
  });

  // 删除已勾选行
  for (let i = selectedIndexes.length - 1; i >= 0; i--) {
    formDataList.value.splice(selectedIndexes[i], 1);
  }

  // 如果没有剩余行数据，添加一行
  if (formDataList.value.length === 0) {
    addRow();
  }
  selectAll.value = false;
};
const toggleSelectAll = () => {
  for (const formData of formDataList.value) {
    formData.selected = selectAll.value === true;
  }
};
const handleAudit = () => {
  if (selectedRows.value.length === 0) {
    alert("请勾选需要审核的数据！");
    return;

    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
  }
  if (confirm("确认审核吗？") == false) {
    return;
  }
  // .then(() => {
  const userName = Cookies.get("userName");
  axios({
    url: "/update/GroupStatus",
    method: "post",
    data: {
      userName: userName,
      id: selectedRows.value.map((row) => row.id),
    },
  }).then((res) => {
    if (res.data.data == 200) {
      alert("审核成功！");
      // selectpurposes();
      searchButton();
      return;
    }
    ElMessage({
      showClose: true,
      message: "审核失败！",
      type: "error",
    });
  });

  // .catch(() => {});
};
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    alert("请勾选需要删除的数据！");
    return;

    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
  }
  if (confirm("确认删除吗？") == false) {
    return;
  }
  // .then(() => {
  const userName = Cookies.get("userName");
  axios({
    url: "/del/BusinessProjectParameterItemMapping",
    method: "post",
    data: {
      id: selectedRows.value[0].id,
    },
  }).then((res) => {
    if (res.data.data == 200) {
      alert("删除成功！");
      // selectpurposes();
      searchButton();
      return;
    }
    ElMessage({
      showClose: true,
      message: "删除失败",
      type: "error",
    });
  });

  // .catch(() => {});
};

// 方法：获取已勾选数据
const getSelectedRowsData = () => {
  const selectedData = formDataList.value.filter((formData) => formData.selected);
  // 在这里可以执行想要的操作，例如将 selectedData 发送到服务器或者在控制台中打印出来
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
//导出数据

//导入数据

// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
selectpurposes();
interface Tree {
  label: string;
  children?: Tree[];
}
</script>

<style scoped>
@media print {
  body * {
    visibility: hidden;
  }
  .print-template,
  .print-template * {
    visibility: visible;
  }
  .print-template {
    position: absolute;
    left: -200px; /* Adjust left value to move the table to the left */
    top: 0;
    width: 100%;
  }
  /* .el-table__header-wrapper {
    display: none !important;
  } */

  /* 隐藏分页 */
  .demo-pagination-block {
    display: none !important;
  }

  /* 调整表格的位置，确保表格主体在纸张内 */
  .el-table__body-wrapper {
    margin-top: 0rem; /* 调整表格与纸张顶部的距离 */
  }
  .el-table__column--selection {
    display: none !important;
  }

  /* 将其他列向前移动一格 */
  /* .el-table__body td:nth-child(2), .el-table__header th:nth-child(2) {
  display: none !important; 
  }隐藏第二列 */

  /* .el-table__body {
  border: none !important;
} */

  /* 隐藏表格单元格的边框 */
  .el-table__body tr {
    border: none !important;
  }

  /* 隐藏表格单元格的格子 */
  /* .el-table__body td, .el-table__body th {
  border: none !important;
} */
  /* 根据需要添加更多打印样式 */
}
/* 悬停 */
/* #f9f9fc, #fef5f0 */
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}
/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.custom-dialog {
  position: fixed;
  top: 12%;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 2px;
  left: 0;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 0; /* 设置横线的垂直位置，可以根据你的布局调整 */
}

.vertical-line3 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.5%; /* 设置横线的垂直位置，可以根据你的布局调整 */
  left: 0%;
}
.title {
  font-size: 18px;
}
.demo-pagination-block {
  float: right;
}
::v-deep .el-table .cell {
  padding: 0;
}
::v-deep .el-header {
  padding: 0;
}
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.buttonHeard {
  position: absolute;
  top: 0%;
  right: 1%;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}

.labs {
  margin-bottom: 0px;
}
/* 子表 */
.sticky-header {
  position: sticky;
  top: -1px;
  background-color: #ddd;
}

.table-header {
  border: 1px solid #ccc;
  background: rgb(225, 225, 230);
  /* width: 50px; */
  z-index: 99;
}

table tr td {
  /* width: 50px; */
  /* width: 10vh; */
  height: 30px;
}

table {
  border-collapse: collapse;
  border: 1px solid #ccc;
  width: 100%;
}

input {
  border: 1px solid transparent;
}

td {
  border: 1px solid #ccc;
}
#buttonmForm {
  position: absolute;
  bottom: 3px;
}
.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.4%; /* 设置横线的垂直位置，可以根据你的布局调整 */
}
.--el-dialog-padding-primary {
  padding: 0;
}
.table-value:hover {
  cursor: pointer;
  z-index: 11;
}
.red-asterisk {
  position: relative;
}
.red-asterisk::before {
  content: "*";
  color: red;
  /* position: absolute;
  left: 5px;
  top: 10px;
  margin-right: 4px; */
}
.dialogDiv {
  position: relative;
  top: 10px;
}
.flex-grow {
  flex-grow: 1;
}
.demo-basic .block:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}
.demo-basic .block {
  flex: 1;
}
::-webkit-scrollbar {
  width: 5px;
}
</style>
